package com.power.aspect;

import com.power.commons.DataScope;
import com.power.model.TRole;
import com.power.model.TUser;
import com.power.query.BaseQuery;
import com.power.util.LoginInfoUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Aspect
@Component
public class DataScopeAspect {
    //对这个注解做切面,只要有这个注解的位置都做拦截
    @Pointcut(value = "@annotation(com.power.commons.DataScope)")
    public void pointCut() {
    }

    @Around(value = "pointCut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //拿到方法上面的注解
        DataScope annotation = method.getDeclaredAnnotation(DataScope.class);
        //拿到注解上的数据
        String tableAlias = annotation.tableAlias();
        String fileField = annotation.fileField();
        //获取到当前用户类型是否是管理员，通过请求头的token获取
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        //通过token解析出来TUser
        TUser tUser = LoginInfoUtil.getUserFromToken(token);
        List<TRole> tRoles = tUser.getTRoles();
        List<String> roleNameList = new ArrayList<>();
        tRoles.forEach(item -> {
            roleNameList.add(item.getRole());
        });
        if (!roleNameList.contains("admin")) {
            //普通用户，拼接过滤条件，查询当前用户能查到的数据
            Object params = joinPoint.getArgs()[0];
            if (Objects.nonNull(params) && params instanceof BaseQuery) {
                ((BaseQuery) params).setFilterSQL(" AND " + tableAlias + "." + fileField + " = " + tUser.getId());
            }
        }
        Object result = joinPoint.proceed();
        System.out.println("DataScopeAspect:process:result=" + result);
        return result;
    }
}
